/*global jQuery, $ */
import { ShopeeProductInfo } from '../models/shopee.models'
import CommonHelper from '../utils/common.helper'
import { PlatformBaseManager } from './platform-base'

export default class ShopeeManager extends PlatformBaseManager {
  init() {
    this.getProductInfo()
      .then((productInfo) => {
        CommonHelper.log('product detected', productInfo)

        jQuery('<button class="btn btn-primary">下载图片展示页</button>')
          .on('click', () => {
            this.saveProductInfo(productInfo)
            //downloadFile(renderProductContent(productInfo), productInfo.title + '.html')
          })
          .appendTo(this.viewContainer)
      })
      .catch(() => {})
  }

  getProductInfo(): Promise<ProductInfo> {
    let paramList = []
    if (location.pathname.startsWith('/product/')) {
      paramList = location.pathname.slice('/product/'.length).split('/')
    } else {
      paramList = location.pathname.split('.').slice(-2)
    }

    let [shopId, itemId] = paramList

    if (!shopId || !itemId) {
      return Promise.reject()
    }
    return fetch(
      `https://my.xiapibuy.com/api/v2/item/get?itemid=${itemId}&shopid=${shopId}`
    )
      .then((resp) => resp.json())
      .then((data) => data.item)
      .then((productInfo: ShopeeProductInfo) => {
        let tierList = productInfo.tier_variations.map((vari) => {
          return {
            title: vari.name,
            options: vari.options.map((title: string, opIdx: number) => {
              return {
                title: title,
                imgUrl: `https://cf.shopee.com.my/file/${vari.images[opIdx]}`,
                fileName: title + '.jpg',
              }
            }),
          }
        })

        let imgList = productInfo.images
          .map((imgId: string, index: number) => ({
            imgUrl: `https://cf.shopee.com.my/file/${imgId}`,
            title: 'main_' + index,
            fileName: 'main_' + index + '.jpg',
          }))
          .filter((img) => {
            return !tierList.some((tier) => {
              return tier.options.some((option) => option.imgUrl === img.imgUrl)
            })
          })
        return {
          title: 'shopee_' + productInfo.name,
          href: location.href,
          //videoList: (productInfo.video_info_list || []).map(video => ({
          //  src: video.
          //})),
          imgList,
          tierList,
        }
      })
  }
}
